import 'package:flutter/material.dart';
import 'email_login_page.dart';
import 'email_service.dart';
import 'email_list_page.dart';

class EmailApp extends StatelessWidget {
  const EmailApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '邮件应用',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const EmailAppStartPage(),
    );
  }
}

class EmailAppStartPage extends StatefulWidget {
  const EmailAppStartPage({super.key});

  @override
  State<EmailAppStartPage> createState() => _EmailAppStartPageState();
}

class _EmailAppStartPageState extends State<EmailAppStartPage> {
  bool _isLoading = true;
  bool _isLoggedIn = false;

  @override
  void initState() {
    super.initState();
    _checkLoginStatus();
  }

  Future<void> _checkLoginStatus() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 尝试加载配置
      final configLoaded = await EmailService.loadConfig();
      if (configLoaded) {
        // 尝试连接
        try {
          await EmailService.testConnection();
          setState(() {
            _isLoggedIn = true;
          });
        } catch (e) {
          // 连接失败，需要重新登录
          debugPrint('自动登录失败: $e');
          setState(() {
            _isLoggedIn = false;
          });
        }
      } else {
        setState(() {
          _isLoggedIn = false;
        });
      }
    } catch (e) {
      setState(() {
        _isLoggedIn = false;
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const CircularProgressIndicator(),
              const SizedBox(height: 16),
              Text('正在加载...', style: Theme.of(context).textTheme.titleMedium),
            ],
          ),
        ),
      );
    }

    if (_isLoggedIn) {
      return const EmailListPage();
    } else {
      return const EmailLoginPage();
    }
  }
}
